package com.iscas.green.extralindextest.servlet;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 服务列表Servlet，直接调用API
 */
@WebServlet(name = "serviceListServlet", urlPatterns = "/service/list")
public class ServiceListServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(ServiceListServlet.class);
    
    private String apiUrl;
    private String defaultAppId;
    private String defaultNamespace;
    
    @Override
    public void init() throws ServletException {
        super.init();
        // 从Spring上下文获取配置值
        try {
            apiUrl = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext())
                    .getEnvironment().getProperty("api.service.url") + "/api/service/getServiceList";
            defaultAppId = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext())
                    .getEnvironment().getProperty("api.service.applicationId", "1864944595792809985");
            defaultNamespace = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext())
                    .getEnvironment().getProperty("api.service.namespace", "default");
            
            log.info("ServiceListServlet初始化成功，apiUrl={}, defaultAppId={}, defaultNamespace={}",
                    apiUrl, defaultAppId, defaultNamespace);
        } catch (Exception e) {
            log.error("从配置文件获取API信息失败", e);
            // 如果获取配置失败，使用默认值
            apiUrl = "http://116.63.51.45:8002/api/service/getServiceList";
            defaultAppId = "1864944595792809985";
            defaultNamespace = "default";
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        log.info("ServiceListServlet收到GET请求");
        
        // 获取参数，如果没有则使用默认值
        String applicationId = request.getParameter("applicationId");
        if (applicationId == null || applicationId.isEmpty()) {
            applicationId = defaultAppId;
        }
        
        String namespace = request.getParameter("namespace");
        if (namespace == null || namespace.isEmpty()) {
            namespace = defaultNamespace;
        }
        
        try {
            // 构建API URL
            String urlString = apiUrl + "?applicationId=" + applicationId + "&namespace=" + namespace;
            log.info("调用API: {}", urlString);
            
            // 创建URL连接
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            
            // 获取响应状态
            int responseCode = conn.getResponseCode();
            log.info("API响应状态码: {}", responseCode);
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String inputLine;
                StringBuilder responseContent = new StringBuilder();
                
                while ((inputLine = in.readLine()) != null) {
                    responseContent.append(inputLine);
                }
                in.close();
                
                // 输出HTML响应
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("<html><body>");
                response.getWriter().println("<h2>服务列表查询结果</h2>");
                response.getWriter().println("<p>应用ID: " + applicationId + "</p>");
                response.getWriter().println("<p>命名空间: " + namespace + "</p>");
                response.getWriter().println("<h3>API响应:</h3>");
                response.getWriter().println("<pre style='background-color:#f5f5f5;padding:10px;overflow:auto;max-height:500px;'>");
                response.getWriter().println(responseContent.toString());
                response.getWriter().println("</pre>");
                response.getWriter().println("</body></html>");
            } else {
                // 输出错误信息
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("<html><body>");
                response.getWriter().println("<h2>API调用失败</h2>");
                response.getWriter().println("<p>HTTP错误码: " + responseCode + "</p>");
                response.getWriter().println("</body></html>");
            }
        } catch (Exception e) {
            log.error("调用API时发生异常", e);
            // 输出异常信息
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println("<html><body>");
            response.getWriter().println("<h2>服务调用异常</h2>");
            response.getWriter().println("<p>错误信息: " + e.getMessage() + "</p>");
            response.getWriter().println("</body></html>");
        }
    }
} 